package com.jiuzhe.commercial.ui.fragment;

import android.Manifest;
import android.app.Dialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.BounceInterpolator;
import android.view.animation.Interpolator;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.Projection;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.services.core.AMapException;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.geocoder.GeocodeAddress;
import com.amap.api.services.geocoder.GeocodeQuery;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.jiuzhe.commercial.R;
import com.jiuzhe.commercial.bean.MapBean;
import com.jiuzhe.commercial.bean.RoomDetailsBean;
import com.jiuzhe.commercial.bean.UserBean;
import com.jiuzhe.commercial.constant.Constants;
import com.jiuzhe.commercial.http.CallBack;
import com.jiuzhe.commercial.http.HttpClient;
import com.jiuzhe.commercial.ui.house.AddHomeStayActivity;
import com.jiuzhe.commercial.ui.house.CityListSelectActivity;
import com.jiuzhe.commercial.ui.house.editor.HomeStayListActivity;
import com.jiuzhe.commercial.utils.SPUtil;
import com.jiuzhe.commercial.utils.UIUtils;
import com.jiuzhe.commercial.view.BannerLayout;

import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * Created by 12078 on 2018/4/19.
 */

public class HouseFragment extends Fragment implements LocationSource, AMapLocationListener, AMap.OnMarkerClickListener, GeocodeSearch.OnGeocodeSearchListener {
    @BindView(R.id.head_title)
    TextView headTitle;
    MapView mMap;
    Unbinder unbinder;
    AMapLocationClient mLocationClient;
    OnLocationChangedListener mListener;
    // 声明mLocationOption对象
    AMapLocationClientOption mLocationOption;
    boolean isFirstLoc = true;
    @BindView(R.id.ib_location)
    ImageView ibLocation;
    @BindView(R.id.ib_add)
    ImageView ibAdd;
    @BindView(R.id.ib_switcher)
    ImageView ibSwitcher;
    @BindView(R.id.tv_location)
    TextView tvLocation;
    @BindView(R.id.map)
    MapView map;
    @BindView(R.id.iv_center_location)
    ImageView ivCenterLocation;

    Unbinder unbinder1;
    private AMap mAmap;
    private LatLng latlng = new LatLng(30.557818, 114.33437);
    private double X = 0.03;
    private MarkerOptions markerOption;
    private UserBean userBean;
    private String mRegionid;
    private UserBean.UserDtoBean userDto;
    private UserBean.UserDtoBean userDtoBean;
    private String token;
    private String id;
    private  GeocodeSearch geocoderSearch; //地理编码
    private String city;
    private float zoom = 12;//地图缩放级别


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View mapLayout = inflater.inflate(R.layout.house_fragment, null);
        mMap = (MapView) mapLayout.findViewById(R.id.map);
        mMap.onCreate(savedInstanceState);
        if (mAmap == null) {
            mAmap = mMap.getMap();
            mAmap.setOnMarkerClickListener(this);
            setUpMap();
        }
        unbinder1 = ButterKnife.bind(this, mapLayout);
        geocoderSearch = new GeocodeSearch(getActivity());
        geocoderSearch.setOnGeocodeSearchListener(HouseFragment.this);
        setTitle();
        return mapLayout;
    }

    private void setTitle() {
        headTitle.setText("房源");
    }


    @OnClick({R.id.ll_location, R.id.ll_add, R.id.ll_switcher})
    public void onclick(View view) {
        switch (view.getId()) {
            case R.id.ll_location:
                Intent intent = new Intent(getActivity(), CityListSelectActivity.class);
                startActivityForResult(intent, 1);
                break;
            case R.id.ll_add:
               UIUtils.startActivity(AddHomeStayActivity.class);
                break;
            case R.id.ll_switcher:
                UIUtils.startActivity(HomeStayListActivity.class);
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 1:
                if (data != null) {
                    city = data.getStringExtra("city");
                    String lat = data.getStringExtra("lat");
                    String lng = data.getStringExtra("lng");

                    tvLocation.setText(city);
                    geocodeSearch(city);

                   // moveCenter(new LatLng(Double.valueOf(lat)*0.000001,Double.valueOf(lng)*0.000001));
                   // addMarkersToMap(Double.valueOf(lat)*0.000001,Double.valueOf(lng)*0.000001);
                }
                break;
            default:
                break;
        }
    }

    private void geocodeSearch(String city) {
        //构造 GeocodeSearch 对象，并设置监听。
        //地理编码事件监听
//通过GeocodeQuery设置查询参数,调用getFromLocationNameAsyn(GeocodeQuery geocodeQuery) 方法发起请求。
//address表示地址，第二个参数表示查询城市，中文或者中文全拼，citycode、adcode都ok
        GeocodeQuery query = new GeocodeQuery(city,city);
        geocoderSearch.getFromLocationNameAsyn(query);
    }


    /**
     * 地图移动 到定位点
     * @param latLng
     */
    private void moveCenter(LatLng latLng) {
        //参数依次是：视角调整区域的中心点坐标、希望调整到的缩放级别、俯仰角0°~45°（垂直与地图时为0）、偏航角 0~360° (正北方为0)
      //  CameraUpdate mCameraUpdate = CameraUpdateFactory.newCameraPosition(new CameraPosition(latLng, 15, 30, 0));
        //AMap类中提供，直接移动过去，不带移动过程动画
      //  mAmap.moveCamera(mCameraUpdate);

        if (null != mAmap) {
            mAmap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, zoom));
        }
    }

    /**
     * 定位设置
     */
    private void setUpMap() {
        //设置显示定位按钮 并且可以点击
        UiSettings settings = mAmap.getUiSettings();
        settings.setScaleControlsEnabled(true);//控制比例尺控件是否显示
        mAmap.setLocationSource(this);//设置了定位的监听,这里要实现LocationSource接口
        mLocationClient = new AMapLocationClient(getActivity());
        //设置定位回调监听，这里要实现AMapLocationListener接口，AMapLocationListener接口只有onLocationChanged方法可以实现，用于接收异步返回的定位结果，参数是AMapLocation类型。
        mLocationClient.setLocationListener(this);
        //初始化定位参数
        mLocationOption = new AMapLocationClientOption();
        //设置定位模式为Hight_Accuracy高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //设置是否返回地址信息（默认返回地址信息）
        mLocationOption.setNeedAddress(true);
        //设置是否只定位一次,默认为false
        mLocationOption.setOnceLocation(true);
        //设置是否强制刷新WIFI，默认为强制刷新
        mLocationOption.setWifiActiveScan(true);
        //设置是否允许模拟位置,默认为false，不允许模拟位置
        mLocationOption.setMockEnable(false);
        //设置定位间隔,单位毫秒,默认为2000ms
        mLocationOption.setInterval(3000);
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        // 设置默认定位按钮是否显示
      //  mAmap.getUiSettings().setMyLocationButtonEnabled(true);
        //启动定位
        mLocationClient.startLocation();
    }


    @Override
    public void onResume() {
        super.onResume();
        //检测系统是否打开开启了地理定位权限
        if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 1);
        }
        //在activity执行onResume时执行mMapView.onResume ()，实现地图生命周期管理
        mMap.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView.onPause ()，实现地图生命周期管理
        mMap.onPause();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mAmap = null;
        isFirstLoc = true;
        mLocationClient.stopLocation();
       ///销毁定位客户端。
        //销毁定位客户端之后，若要重新开启定位请重新New一个AMapLocationClient对象。
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mAmap = null;
        if (mMap != null) {
            mMap.onDestroy();
        }
        if (unbinder1 != null) {
            unbinder1.unbind();
        }

        if (mLocationClient != null) {
            mLocationClient.stopLocation();//停止定位
            mLocationClient.onDestroy();
        }
    }

    @Override
    public void activate(OnLocationChangedListener onLocationChangedListener) {
        mListener = onLocationChangedListener;
    }

    @Override
    public void deactivate() {
        mListener = null;
    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (aMapLocation != null) {
            if (aMapLocation.getErrorCode() == 0) {
                //定位成功回调信息，设置相关消息
                aMapLocation.getLocationType();//获取当前定位结果来源，如网络定位结果，详见官方定位类型表
                double latitude = aMapLocation.getLatitude();
                double longitude = aMapLocation.getLongitude();//获取经度
                String city = aMapLocation.getCity();
                // 城市信息 aMapLocation.getCity();//城市信息

                // 如果不设置标志位，此时再拖动地图时，它会不断将地图移动到当前的位置
                if (isFirstLoc) {
                    tvLocation.setText(aMapLocation.getCity());
                    //设置缩放级别
                  //  mAmap.moveCamera(CameraUpdateFactory.zoomTo(12));
                    //将地图移动到定位点
                    mAmap.moveCamera(CameraUpdateFactory.changeLatLng(new LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude())));
                    //点击定位按钮 能够将地图的中心移动到定位点
                  //  mListener.onLocationChanged(aMapLocation);
                    isFirstLoc = false;
                    mAmap.clear();
                    addMarkersToMap(city);
                }
            } else {
                //显示错误信息ErrCode是错误码，errInfo是错误信息，详见错误码表。
                Log.e("AmapError", "location Error, ErrCode:"
                        + aMapLocation.getErrorCode() + ", errInfo:"
                        + aMapLocation.getErrorInfo());
             //   Toast.makeText(getActivity(), "定位失败", Toast.LENGTH_LONG).show();
                mLocationClient.startLocation();
            }
        }
    }

    /**
     * 地图上添加 图标
     * @param
     * @param
     */
    private void addMarkersToMap(String city) {
          // mAmap.clear();
        //Double lng1 = new Double(longitude);
        //Double lat1 = new Double(latitude);
       // Double x = new Double(X);
        double latChange = 0.046628;//纬度5公里变化 0.046628
        double lngChange = 0.051327;//经度5公里变化 0.051327
     //   String lng = String.valueOf(new Double(lng1.doubleValue() - x.doubleValue()) + "-" + new Double(lng1.doubleValue() + x.doubleValue()));
     //   String lat = String.valueOf(new Double(lat1.doubleValue() - x.doubleValue()) + "-" + new Double(lat1.doubleValue() + x.doubleValue()));
        /*int beginLat = (int) NumberUtil.mul(NumberUtil.sub(latitude,latChange),1000000);
        int endLat = (int) NumberUtil.mul(NumberUtil.add(latitude,latChange),1000000);
        int beginLng = (int) NumberUtil.mul(NumberUtil.sub(longitude,lngChange),1000000);
        int endLng = (int) NumberUtil.mul(NumberUtil.add(longitude,lngChange),1000000);*/

        HashMap<String, String> map = new HashMap<>();
        map.put("merchantId", SPUtil.getString(getActivity(),Constants.MERCHANTID));
       // map.put("beginLng", String.valueOf(beginLng));
      //  map.put("endLng", String.valueOf(endLng));
      //  map.put("beginLat", String.valueOf(beginLat));
      //  map.put("endLat", String.valueOf(endLat));
        map.put("cityName", city);
        token = SPUtil.getString(getActivity(), Constants.TOKEN);
        id = SPUtil.getString(getActivity(), Constants.ID);
        String autoSignStr = Constants.MAP_MARKERS.substring(Constants.MAP_MARKERS.lastIndexOf("0/")+1) + "?token=";
        String signStr = UIUtils.Md5(autoSignStr + token);
        map.put("token", id);
        map.put("sign", signStr);
        HttpClient.post(this, Constants.MAP_MARKERS, map, new CallBack<List<MapBean>>() {

            int sumLats = 0;
            int sumLngs = 0;
            int total=0;
                    @Override
                    public void onSuccess(List<MapBean> result) {
                        if (result.size()>0){
                            for (MapBean dataBean : result) {
                                markerOption = new MarkerOptions()
                                        .title(dataBean.getSkuId())
                                        .period(dataBean.getRoomStatus())
                                        .icon(BitmapDescriptorFactory.fromView(getView(dataBean.getPrice(),dataBean.getRoomStatus())))
                                        .position(new LatLng(Double.valueOf(dataBean.getLat()) * 0.000001, Double.valueOf(dataBean.getLng()) * 0.000001))
                                        .draggable(false);
                               // setMapView(dataBean.getRoomStatus());
                                mAmap.addMarker(markerOption);
                                sumLats += dataBean.getLat();
                                sumLngs += dataBean.getLng();
                            }
                            total = result.size();
                            double  anLat = (double) sumLats / total;
                            double  anIng = (double)sumLngs / total;
                            //moveCenter(new LatLng(Double.valueOf(anInt) * 0.000001, Double.valueOf(anInt1) * 0.000001));
                            moveCenter(new LatLng(anLat * 0.000001, anIng * 0.000001));
                        }else {
                            UIUtils.showToastSafe("附近暂无房源");
                        }
                      }
                    });
    }

    private void setMapView(int status) {
        if (status == 1){
            markerOption.icon(BitmapDescriptorFactory.fromResource(R.mipmap.hotel_a)); //图标
        }else if(status == 5){
            markerOption.icon(BitmapDescriptorFactory.fromResource(R.mipmap.hotel_c)); //图标
        }
    }


    protected View getView(String price,int status) {
        View view = getActivity().getLayoutInflater().inflate(R.layout.map_item_view, null);
        ImageView iv = view.findViewById(R.id.image);
        TextView textView = (TextView) view.findViewById(R.id.textView);
        textView.setText(price);
       if (status == 1){
           iv.setImageResource(R.mipmap.hotel_a);
        }else if(status == 5){
          // iv.setBackground(getResources().getDrawable(R.drawable.ic_room_marker_gray_bg2));
           iv.setImageResource(R.mipmap.hotel_c);
        }
        return view;
    }

    @Override
    public boolean onMarkerClick(Marker marker) {
        if (mAmap != null) {
            jumpPoint(marker);
            showRoomDetail(marker.getTitle());
        }
        switch (marker.getPeriod()){
            case 1://可预定   绿色
                //showRoomDetail(marker.getTitle());
               break;
            case 5://维修房 红色
                UIUtils.showToastSafe("该房间已下架");
                break;
        }
        return true;
    }


    /**
     * marker点击时跳动一下
     */
    private void jumpPoint(final Marker marker) {
        final Handler handler = new Handler();
        final long start = SystemClock.uptimeMillis();
        Projection proj = mAmap.getProjection();
        final LatLng markerLatlng = marker.getPosition();
        Point markerPoint = proj.toScreenLocation(markerLatlng);
        markerPoint.offset(0, -100);
        final LatLng startLatLng = proj.fromScreenLocation(markerPoint);
        final long duration = 1500;

        final Interpolator interpolator = new BounceInterpolator();
        handler.post(new Runnable() {
            @Override
            public void run() {
                long elapsed = SystemClock.uptimeMillis() - start;
                float t = interpolator.getInterpolation((float) elapsed
                        / duration);
                double lng = t * markerLatlng.longitude + (1 - t)
                        * startLatLng.longitude;
                double lat = t * markerLatlng.latitude + (1 - t)
                        * startLatLng.latitude;
                marker.setPosition(new LatLng(lat, lng));
                if (t < 1.0) {
                    handler.postDelayed(this, 16);
                }
            }
        });
    }


    /**
     * 查看房间详情
     * @param skuId
     */
    private void showRoomDetail(String skuId) {
        final  Dialog alertDialog = new Dialog(getActivity(), R.style.EasyListDialogStyle);
        alertDialog.show();
        Window window = alertDialog.getWindow();
        window.setContentView(R.layout.pop_marker);
        window.setGravity(Gravity.BOTTOM);
        DisplayMetrics dm = new DisplayMetrics();
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.width = (int) (dm.widthPixels);
        window.setAttributes(lp);
        Button btEdit = (Button) alertDialog.findViewById(R.id.bt_edit);
        final TextView tvRoomName = (TextView) alertDialog.findViewById(R.id.tv_roomName);
        final TextView tvRoomAddress = (TextView) alertDialog.findViewById(R.id.tv_roomAddress);
        final TextView tvPrice = (TextView) alertDialog.findViewById(R.id.textView4);
        final TextView tvRoomBond = (TextView) alertDialog.findViewById(R.id.textView5);
        final TextView tvStatus = (TextView) alertDialog.findViewById(R.id.tv_status);
        final TextView tvConfig = (TextView) alertDialog.findViewById(R.id.tv_config);
        final ImageView ivWifi =  alertDialog.findViewById(R.id.iv_wifi);
        final ImageView ivBed =  alertDialog.findViewById(R.id.iv_bed);
        final ImageView ivBathroom =  alertDialog.findViewById(R.id.iv_bathroom);
        final ImageView ivWindow =  alertDialog.findViewById(R.id.iv_window);
        final BannerLayout bannerLayout =  alertDialog.findViewById(R.id.banner);
        HashMap<String, String> map = new HashMap<>();
        map.put("skuId", skuId);

        String autoSignStr = Constants.ROOM_DETAIL.substring(Constants.ROOM_DETAIL.lastIndexOf("0/")+1) + "?token=";
        String signStr = UIUtils.Md5(autoSignStr + token);
        map.put("token", id);
        map.put("sign", signStr);
        String url = Constants.ROOM_DETAIL + "?token=" + id + "&sign=" + signStr;
        HttpClient.post(this, Constants.ROOM_DETAIL, map, new CallBack<RoomDetailsBean>() {
            @Override
            public void onSuccess(RoomDetailsBean result) {
                if (result != null){
                    tvRoomName.setText(result.getSkuName());
                    tvRoomAddress.setText(result.getAddress() + "  " + result.getRoomNo());
                    tvPrice.setText(result.getPrice() + "");
                    tvRoomBond.setText(result.getRoomBond() + "");
                    if (result.getRoomStatus()==5){
                        Resources resources= getActivity().getBaseContext().getResources();
                        Drawable drawable=resources.getDrawable(R.drawable.bg_care);
                        tvStatus.setBackground(drawable);
                        tvStatus.setText("已下架");
                    }
                    String type = result.getRoomType();
                    if (("0").equals(type)){
                        tvConfig.setText(result.getBedroomNum() + "室" + result.getToiletNum() + "卫" + "  公寓型");
                    }else if (("1").equals(type)){
                        tvConfig.setText(result.getBedroomNum() + "室" + result.getToiletNum() + "卫" + "  酒店型");
                    }else if (("2").equals(type)){
                        tvConfig.setText(result.getBedroomNum() + "室" + result.getToiletNum() + "卫" + "  住宅型");
                    }

                    List<String> facilityIds = result.getFacilityIds();
                    List<String> imgUrls =  result.getImgUrls();
                    if (facilityIds != null && facilityIds.size() > 0){
                        for (String facilityId : facilityIds) {
                            if ("101".equals(facilityId)){
                                ivWifi.setVisibility(View.VISIBLE);
                            }else if ("102".equals(facilityId)){
                                ivBed.setVisibility(View.VISIBLE);
                            }else if ("103".equals(facilityId)){
                                ivBathroom.setVisibility(View.VISIBLE);
                            }else if ("104".equals(facilityId)){
                                ivWindow.setVisibility(View.VISIBLE);
                            }
                        }
                    }
                    if (imgUrls!= null && imgUrls.size()>0){
                        bannerLayout.setViewUrls(imgUrls);
                    }else {
                        imgUrls.add("");
                        bannerLayout.setViewUrls(imgUrls);
                    }
                }
            }
        });

        btEdit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                UIUtils.startActivity(HomeStayListActivity.class);
                alertDialog.dismiss();
            }
        });
    }

    @Override
    public void onRegeocodeSearched(RegeocodeResult regeocodeResult, int i) {

    }

    @Override
    public void onGeocodeSearched(GeocodeResult geocodeResult, int i) {
        if (i == AMapException.CODE_AMAP_SUCCESS) {
            if (geocodeResult != null && geocodeResult.getGeocodeAddressList() != null
                    && geocodeResult.getGeocodeAddressList().size() > 0) {
                GeocodeQuery  a  =   geocodeResult.getGeocodeQuery();
                GeocodeAddress address = geocodeResult.getGeocodeAddressList().get(0);
                String addressName = "经纬度值:" + address.getLatLonPoint() + "\n位置描述:"
                        + address.getFormatAddress();
                //获取到的经纬度
                LatLonPoint latLongPoint = address.getLatLonPoint();
                double Lat = (float)latLongPoint.getLatitude();
                double Lon = (float)latLongPoint.getLongitude();
                moveCenter(new LatLng(Lat,Lon));
                addMarkersToMap(city);
            }
        }
    }
}
